package com.singerw.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import com.singerw.service.TwOptionsService;
import com.singerw.utils.RedisUtils;
import com.singerw.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @version V1.0
 * @Package com.singerw.filter
 * @auhter 张欣
 * @date 2021/1/26-7:52 PM
 */
@Component
public class VerifyCodeFilter extends GenericFilterBean {


    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private TwOptionsService twOptionsService;
    private String defaultFilterProcessUrl = "/auth/login";


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
            //直接处理数据为 JSONObject 方便后面登录拦截器使用
            JSONObject jsonObject = null;
            try {
                BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
                StringBuilder responseStrBuilder = new StringBuilder();
                String inputStr;
                while ((inputStr = streamReader.readLine()) != null)
                    responseStrBuilder.append(inputStr);

                jsonObject = JSONObject.parseObject(responseStrBuilder.toString());

            } catch (Exception e) {
                e.printStackTrace();
            }
            request.getSession().setAttribute("data", jsonObject);
            Boolean loginCheck = twOptionsService.getRoutineSettings().getBoolean("loginCheck");
            if (loginCheck) {

                String requestCaptcha = jsonObject.getString("VerificationCode");
                String genCaptcha = redisUtils.get(jsonObject.getString("token"));

                if (StringUtils.isEmpty(requestCaptcha) || !genCaptcha.toLowerCase().equals(requestCaptcha.toLowerCase())) {

                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json; charset=utf-8");
                    response.getWriter().write(JSON.toJSONString(ResultUtils.fail("验证码错误")));
                    return;
                }

            }

        }

        filterChain.doFilter(request, response);

    }
}
